package com.woniuxy.stage3demo.controller.controllerhpd;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.woniuxy.stage3demo.bean.ResultMsg;
import com.woniuxy.stage3demo.bean.hpd.ChannelBean;
import com.woniuxy.stage3demo.mapper.mapperhpd.ChannelMapper;
import com.woniuxy.stage3demo.pageHelper.PageRequest;
import com.woniuxy.stage3demo.pageHelper.TableResult;
import com.woniuxy.stage3demo.service.servicehpd.IChannelService;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@RequestMapping("/channel")
@RestController
public class ChannelController {
    @Resource
    private IChannelService channelServiceImpl;
    @Resource
    private ChannelMapper channelMapper;

    //分页查询
    @RequestMapping(value = "/page",produces = {"application/json;charset=utf-8"})
    public TableResult<ChannelBean> findAllByParams(PageRequest request, ChannelBean channelBean){
        PageInfo<ChannelBean> pageInfo = channelServiceImpl.findAllByParams(request, channelBean);
        return new TableResult<>(pageInfo.getTotal(),pageInfo.getList());
    }

    //更改渠道状态
    @PutMapping(value = "/status/{id}/{status}",produces = {"application/json;charset=utf-8"})
    public ResultMsg statusUpdate(@PathVariable("id") Long id, @PathVariable("status") Integer status){
        ResultMsg res = new ResultMsg(200,"操作成功",null);
        int opt;
        if(id != null && status != null) {
            if (status==1){
                opt=1;
            }else {
                opt=0;
            }
           channelServiceImpl.updateChannelStatus(opt,id);

            return res;
        }else{
            res.setCode(10000);
            res.setMsg("更改失败");
            return res;
        }
    }

    //批量更改渠道状态
    @PutMapping(value = "/mulOpt/{ids}/{selOpt}",produces = {"application/json;charset=utf-8"})
    public ResultMsg mulStatusUpdate(@PathVariable("ids") Long ids[],@PathVariable("selOpt") int selOpt){
        ResultMsg res = new ResultMsg(200,"操作成功",null);
        for (Long id:ids) {
            channelServiceImpl.updateChannelStatus(selOpt,id);
        }
        return res;
    }



    @DeleteMapping(value = "/{id}",produces = {"application/json;charset=utf-8"})
    public ResultMsg channelDel(@PathVariable("id") Long id){
        ResultMsg res = new ResultMsg(200,"操作成功",null);
        if(id != null) {
            channelServiceImpl.deleteChannel(id);
            return res;
        }else{
            res.setCode(10000);
            res.setMsg("更改失败");
            return res;
        }
    }

    @PutMapping(value = "/info",produces = {"application/json;charset=utf-8"})
    public ResultMsg update(@RequestBody ChannelBean channelBean){
        ResultMsg res = new ResultMsg(200,"操作成功",null);
        if(channelServiceImpl.updateChannel(channelBean) == 1){
            return res;
        }else{
            res.setCode(10000);
            res.setMsg("修改失败");
            return res;
        }
    }

    @PostMapping(value = "/add",produces = {"application/json;charset=utf-8"})
    public ResultMsg addChannel(@RequestBody ChannelBean channelBean){
        ResultMsg res = new ResultMsg(200,"操作成功",null);
        if(channelServiceImpl.addChannel(channelBean) == 1){
            return res;
        }else{
            res.setCode(10000);
            res.setMsg("修改失败");
            return res;
        }
    }




    //数据导出为excel
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletResponse response) throws IOException {
        ChannelBean channelBean=new ChannelBean();
        List<ChannelBean> channels = channelMapper.findAllByParams(new PageRequest(),channelBean);

        XSSFWorkbook wb = new XSSFWorkbook();         //excel2007
        XSSFSheet sheet = wb.createSheet("channel");
        XSSFRow row = null;

        row = sheet.createRow(0);  //创建第一个单元格，用于标题
        row.setHeight((short)(26.25 * 20));
        row.createCell(0).setCellValue("渠道列表"); //为第一行单元格设值

        //为标题设计空间
        CellRangeAddress rowRegion = new CellRangeAddress(0,0,0,6);
        sheet.addMergedRegion(rowRegion);

        /*动态获取数据库列表
         * */
        //设置列头
        row = sheet.createRow(1);
        row.setHeight((short)(22.5 * 20)); //设置行高
        row.createCell(0).setCellValue("id");//为第一个单元格设值
        row.createCell(1).setCellValue("公司名称"); //为第二个单元格设值
        row.createCell(2).setCellValue("所在地区");
        row.createCell(3).setCellValue("级别");
        row.createCell(4).setCellValue("联系人");
        row.createCell(5).setCellValue("联系方式");
        row.createCell(6).setCellValue("来源");

        for(int i = 0; i < channels.size(); i++){   // 数据动态存入表格
            row = sheet.createRow(i + 2);
            ChannelBean channel = channels.get(i);

            row.createCell(0).setCellValue(channel.getId());
            row.createCell(1).setCellValue(channel.getCompanyName());
            row.createCell(2).setCellValue(channel.getCompanyArea());
            row.createCell(3).setCellValue(channel.getChannelLevel());
            row.createCell(4).setCellValue(channel.getContacts());
            row.createCell(5).setCellValue(channel.getContactsPhone());
            row.createCell(6).setCellValue(channel.getSource());


        }
        sheet.setDefaultRowHeight((short)(16.5 * 20));
        //列表自适应
        for (int i = 0; i <= 13; i++){
            sheet.autoSizeColumn(i);
        }

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        OutputStream os = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment;filename=channel.xlsx");//默认Excel名称
        wb.write(os);
        os.flush();
        os.close();

    }

    @RequestMapping("/import")
    public JSONObject exImport(@RequestParam(value = "filename") MultipartFile file, HttpSession session) {
        JSONObject json_send = new JSONObject();
        int a = 0;

        String fileName = file.getOriginalFilename();
        try {
            json_send = channelServiceImpl.batchImport(fileName, file);
        }catch (Exception e){
            e.printStackTrace();
        }
        return json_send;
    }

}
